package com.example.taobaolianmeng.ui.fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.viewpager.widget.ViewPager;

import com.example.taobaolianmeng.R;
import com.example.taobaolianmeng.base.BaseFragment;
import com.example.taobaolianmeng.model.domain.Categories;
import com.example.taobaolianmeng.presenter.IHomePresenter;
import com.example.taobaolianmeng.ui.adapter.HomePageAdapter;
import com.example.taobaolianmeng.utils.PresenterManger;
import com.example.taobaolianmeng.view.IHomeCallBack;
import com.google.android.material.tabs.TabLayout;

import butterknife.BindView;

public class HomeFragment extends BaseFragment implements IHomeCallBack {


    private static final String TAG = "HomeFragment";
    private IHomePresenter mHomePresenter;

    @BindView(R.id.home_indicator)
    public TabLayout mTabLayout;

    @BindView(R.id.home_pager)
    public ViewPager homePager;
    private HomePageAdapter mHomePageAdapter;

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View rootView) {
        mTabLayout.setupWithViewPager(homePager);
        //给viewPager设置适配器
        mHomePageAdapter = new HomePageAdapter(getChildFragmentManager());
        homePager.setAdapter(mHomePageAdapter);
    }

    @Override
    protected void initPresenter() {
        mHomePresenter = PresenterManger.getInstance().getHomePresenter();
        mHomePresenter.registerViewCallback(this);
    }

    @Override
    protected View loadRootView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.base_home_fragment_layout,container,false);
    }

    @Override
    protected void loadData() {
        mHomePresenter.getCategories();
    }

    @Override
    public void onCategoriesLoad(Categories categories) {
        Log.d(TAG,"onCategoriesLoad..");
         setupState(State.SUCCESS);
        //加载的数据从这里回来
        if(mHomePresenter !=null){
            //加载全部页面
//            homePager.setOffscreenPageLimit(categories.getData().size());
            mHomePageAdapter.setCategories(categories);
        }
    }

    @Override
    public void onNetworkError() {
        setupState(State.ERROR);
    }

    @Override
    public void onLoading() {
        setupState(State.LOADING);
    }

    @Override
    public void onEmpty() {
        setupState(State.EMPTY);
    }

    @Override
    protected void release() {
        //取消注册回调
        if (mHomePresenter!=null) {
            mHomePresenter.unregisterViewCallback(this);
        }
    }

    @Override
    protected void onRetryClick() {
        //网络错误点击重试
        //重新加载匪类内容
        if(mHomePresenter != null){
            mHomePresenter.getCategories();
        }
    }
}
